package main.controller;

import java.util.List;

import main.dao.BoyRepository;
import main.entity.Boy;
import main.service.BoysService;
import main.util.ResultData;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@SpringBootApplication
@RestController
public class BoyController {
	
	@Autowired
	private BoyRepository boyRepository;
	
	@Autowired
	private BoysService boysService;
	
	/**
	 * 查询所有男生列表
	 * @return
	 */
	@RequestMapping(value="/boys",method=RequestMethod.GET)
	public List<Boy> boyList(){
		return boyRepository.findAll();
	}
	
/*	*

	 * @param cupSize
	 * @param age
	 * @return*/

	/**
	 * 添加一个男生
	 * @param cupSize
	 * @param age
	 * @return
	 */
	@RequestMapping(value="/addBoy",method=RequestMethod.POST)
	public ResultData addBoy(@Validated Boy boy,BindingResult bindingResult) {

		if(bindingResult.hasErrors()) {
			return ResultData.generateFailResultData(bindingResult.getFieldError().getDefaultMessage());
		}
		
		boy.setAddress(boy.getAddress());
		boy.setName(boy.getName());
		boy.setAge(boy.getAge());
		
		return ResultData.generateSuccessResultData("成功！", boyRepository.save(boy));
	}
	
	/**
	 * 查询一个男生
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/boy/{id}",method=RequestMethod.GET)
	public Boy getBoy(@PathVariable("id") Integer id) {
		return boyRepository.findOne(id);
	}
	
	/**
	 * 修改一条数据
	 * @param id
	 * @param cupSize
	 * @param age
	 * @return
	 */
	@RequestMapping(value="/updateBoy/{id}",method=RequestMethod.POST)
	public Boy updateBoy(@PathVariable("id") Integer id,
						 @RequestParam("cupSize") String cupSize,
						 @RequestParam("age") Integer age) {
		Boy boy = new Boy();
		boy.setId(id);
		boy.setAge(age);
		return boyRepository.save(boy);
	}
	
	/**
	 * 删除一条数据
	 * @param id
	 */
	@RequestMapping(value="/delete/{id}",method=RequestMethod.DELETE)
	public void deleteBoy(@PathVariable("id") Integer id) {
		boyRepository.delete(id);
	}
	
	/**
	 * 通过年龄查询
	 * @param age
	 * @return
	 */
	@RequestMapping(value="/boyList/age/{age}",method=RequestMethod.GET)
	public List<Boy> boyListByAge(@PathVariable("age") Integer age) {
		return boyRepository.findByAge(age);
	}
	
	@RequestMapping(value="/insertTwo",method=RequestMethod.POST)
	public void insertBoy() {
		boysService.insertBoy();
	}
	
	@RequestMapping(value="/boyList/getAge/{id}",method=RequestMethod.GET)
	public void getBoyAge(@PathVariable("id") Integer id) throws Exception {
		boysService.getAge(id);
	}
	
}
